package com.nineclock.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.system.dto.SysCompanyDTO;
import com.nineclock.system.dto.SysCompanyUserDTO;
import com.nineclock.system.dto.SysRoleDTO;
import com.nineclock.system.dto.SysUserDTO;
import com.nineclock.system.mapper.*;
import com.nineclock.system.pojo.*;
import com.nineclock.system.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Service
@Transactional
public class TestServiceImpl implements TestService {
    @Autowired
    SysCompanyMapper companyMapper;

    @Autowired
    SysCompanyUserMapper companyUserMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    SysRoleMapper roleMapper;

    @Autowired
    SysCompanyUserRoleMapper companyUserRoleMapper;

    @Autowired
    SysUserMapper userMapper;


    /**
     * 根据系统用户id查询 企业列表
     * @param userId
     * @return
     */
    @Override
    public List<SysCompanyDTO> queryCompanyListByUserId(Long userId) {
        if(userId == null){
            //throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        //根据 系统用户id 查询 企业员工列表
        LambdaQueryWrapper<SysCompanyUser> companyUserQw = new LambdaQueryWrapper<>();

        companyUserQw.eq(SysCompanyUser::getUserId, userId);
        //获取企业员工列表
        List<SysCompanyUser> companyUserList = companyUserMapper.selectList(companyUserQw);
        if(CollectionUtil.isEmpty(companyUserList)){
            //throw new NcException(ResponseEnum.USER_NOT_JOIN_COMPANY);
        }
        //从企业员工列表中获取 企业id
        //map 可以把集合转换为一个新的集合
        //collect(Collectors.toSet()) 指定要转换成什么集合类型
        Set<Long> companyIds = companyUserList.stream().map(companyUser -> {
            return companyUser.getCompanyId();
        }).collect(Collectors.toSet());

        //再根据企业id获取 企业列表信息
        LambdaQueryWrapper<SysCompany> companyQw = new LambdaQueryWrapper<>();
        companyQw.in(SysCompany::getId, companyIds);

        List<SysCompany> companyList = companyMapper.selectList(companyQw);


        //转换为DTO
        List<SysCompanyDTO> companyDTOList = BeanHelper.copyWithCollection(companyList, SysCompanyDTO.class);

        return companyDTOList;
    }

    @Override
    public List<SysCompanyUserDTO> queryCompanyUser(Long companyId, Long userId) {
        //健壮性的判断
        if(companyId == null && userId == null){
            //throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        LambdaQueryWrapper<SysCompanyUser> companyUserQw = new LambdaQueryWrapper<>();
        //判断是否是有效的员工信息
        companyUserQw.eq(SysCompanyUser::getEnable, 1);
        if(userId != null){
            companyUserQw.eq(SysCompanyUser::getUserId, userId);
        }

        if(companyId != null){
            companyUserQw.eq(SysCompanyUser::getCompanyId, companyId);
        }
        //查询得到员工列表
        List<SysCompanyUser> companyUserList = companyUserMapper.selectList(companyUserQw);

        //健壮性的判断
        if(CollectionUtil.isEmpty(companyUserList)){
           // throw new NcException(ResponseEnum.USER_NOT_JOIN_COMPANY);
        }

        //转换为DTO列表
        List<SysCompanyUserDTO> companyUserDTOList = BeanHelper.copyWithCollection(companyUserList, SysCompanyUserDTO.class);

        //组装角色信息
        companyUserDTOList.forEach(companyUserDTO -> {
            //根据每一个员工获取对应的角色信息
            LambdaQueryWrapper<SysCompanyUserRole> companyUserRoleQw = new LambdaQueryWrapper<>();
            companyUserRoleQw.eq(SysCompanyUserRole::getCompanyUserId,companyUserDTO.getId() );
            companyUserRoleQw.eq(SysCompanyUserRole::getCompanyId, companyUserDTO.getCompanyId());

            List<SysCompanyUserRole> companyUserRoleList = companyUserRoleMapper.selectList(companyUserRoleQw);
            if(CollectionUtil.isNotEmpty(companyUserRoleList)){
                //把中间的中的角色id取出来
                Set<Long> roleIds = companyUserRoleList.stream().map(sysCompanyUserRole -> {
                    return sysCompanyUserRole.getRoleId();
                }).collect(Collectors.toSet());


                LambdaQueryWrapper<SysRole> roleQw = new LambdaQueryWrapper<>();
                roleQw.in(SysRole::getId, roleIds);

                List<SysRole> roleList = roleMapper.selectList(roleQw);
                //转换为DTO数据
                List<SysRoleDTO> sysRoleDTOS = BeanHelper.copyWithCollection(roleList, SysRoleDTO.class);

                companyUserDTO.setRoles(sysRoleDTOS);

            }

        });

        return companyUserDTOList;
    }


    /**
     * 根据用户名 或者 手机号码 查询用户信息
     * @param username
     * @return
     */
    @Override
    public SysUserDTO queryUser(String username) {

        LambdaQueryWrapper<SysUser> userQw = new LambdaQueryWrapper<>();
        //用户名，或 是手机号都可以
        userQw.eq(SysUser::getUsername, username).or().eq(SysUser::getMobile, username);

        SysUser user = userMapper.selectOne(userQw);
        //转换为DTO数据
        SysUserDTO sysUserDTO = BeanHelper.copyProperties(user, SysUserDTO.class);

        return sysUserDTO;
    }
}
